package 剑指offer;

import java.util.HashMap;

/**
 * @description:
 * @author: ywk
 * @date: 2021-03-13
 */
public class 情侣握手 {
    private static int count = 0;
    private static final HashMap<Integer, Integer> position = new HashMap<>();

    public static int minSwapsCouples(int[] row) {
        for (int i = 0; i < row.length; i++) {
            position.put(row[i], i);
        }
        for (int g = 0; g < row.length / 2; g++) {
            int c1 = row[2 * g];
            int c2 = row[2 * g + 1];
            if ((c1 % 2 == 0 && c2 != c1 + 1) || (c1 % 2 != 0 && c2 != c1 - 1)) {
                int target_pos = c1 % 2 == 0 ? position.get(c1 + 1) : position.get(c1 - 1);
                swap(row, 2 * g + 1, target_pos);
                count++;
            }
        }
        return count;
    }

    private static void swap(int[] row, int i, int j) {
        int tmp = row[i];
        row[i] = row[j];
        row[j] = tmp;
        position.put(row[i], i);
        position.put(row[j], j);
    }

    public static void main(String[] args) {
        System.out.println(minSwapsCouples(new int[]{0, 2, 1, 3}));
    }
}
